package com.lans.linear;

import java.util.Iterator;

/**
 * @author: lans
 * @date: 2025/2/25
 * @name: 刘宇
 */
public class SymbolTable implements Iterable{

    private Node head;

    private int N;

    public SymbolTable() {
        head = new Node(null,null,null);
        N=0;
    }

    //根据键获取value值
    public String getValue(String key){
        Node n = head.next;
        while(n.next!=null){
            n = n.next;
            if(n.key.equals(key)){
                return n.value;
            }
        }
        return null;
    }

    //添加键值对
    public void put(String key,String value){
        Node n = head;
        while(n.next!=null){
            n = n.next;
            //当前符号表中存在该key,存在则覆盖原来的value
            if(n.key.equals(key)){
                n.value = value;
            }
        }
        //不存在则添加新的键值对
        Node oldFirst = head.next;
        Node node = new Node(key,value,oldFirst);
        head.next = node;
        N++;
    }

    //根据键删除value值
    public void delVal(String key){
        Node n = head;
        while(n.next!=null){
            if(n.key.equals(key)){
                n.next=n.next.next;
                N--;
            }
            n = n.next;
        }
    }

    public int size(){
        return N;
    }



    @Override
    public Iterator iterator() {
        return new MyIterator();
    }

    private class MyIterator implements Iterator{
        private Node n = head;
        @Override
        public boolean hasNext() {
            return n.next != null;
        }

        @Override
        public Object next() {
            Node node= n.next;
            n=n.next;
            return node.key;
        }
    }
    private class Node{
        private String key;
        private String value;
        private Node next;

        public Node(String key, String value, Node next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        SymbolTable symbolTable = new SymbolTable();
        symbolTable.put("key1","东皇太一");
        symbolTable.put("key2","司空震");
        symbolTable.put("key3","元歌");
        symbolTable.put("key4","马超");
        System.out.println(symbolTable.getValue("key3"));
        symbolTable.delVal("key3");
        System.out.println(symbolTable.getValue("key3"));
    }
}